<!-- 个人资料设置 -->
<template>
  <div class="userInfom">
    <a-modal
      class="inform-modal"
      title="个人设置"
      width="800px"
      :visible="informVisible"
      @cancel="handleCancel"
    >
      <a-form-model
        ref="form"
        :model="informData"
        :rules="rules"
        :colon="false"
        v-bind="formLayout"
        class="inform-form"
        style="height:auto;"
      >
        <!-- 个人信息 -->
        <a-row :gutter="24">
          <div class="info-header">
            <a-icon type="idcard" theme="filled"/>
            <span>基本信息</span>
          </div>
          <a-col :span="4">
            <a-form-model-item prop="userAvatar">
              <AvatarUpload @ok="uploadOk" :photoUrl="informData.photo"></AvatarUpload>
            </a-form-model-item>
          </a-col>
          <a-col :span="20">
            <a-row :gutter="24">
              <a-col :span="24">
                <a-form-model-item label="用户名" prop="userName">
                  <span>{{informData.loginName}}</span>
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="24">
                <a-form-model-item label="手机号码" prop="userPhone">
                  <span>{{userPhone}}</span>
                  <a style="marginLeft: 24px" @click="mobileEdit()">修改</a>
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="24">
                <a-form-model-item label="邮箱账号" prop="userEmail" v-show="isEmailEdit===false">
                  <span>{{informData.email}}</span>
                  <a style="marginLeft: 24px;" @click="emailEdit()">修改</a>
                </a-form-model-item>
                <a-form-model-item label="邮箱" prop="userEmail" v-show="isEmailEdit===true">
                  <a-input style="width: 80%" v-model="informData.email" autocomplete="off" />
                  <!-- <i @click="emailSubmit" class="iconfont iconsuccess"></i> -->
                  <i @click="cancelEmailSubmit" class="iconfont iconerror" style="color:red"></i>
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="24">
                <a-form-model-item label="单位名称" prop="userOrgName">
                  <a-input
                    class="input-unitName"
                    v-model="informData.unitName"
                    autocomplete="off"
                    disabled
                  />
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="24">
                <a-form-model-item label="注册时间" prop="createTime">
                  <span>{{informData.createTime}}</span>
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-divider />
        </a-row>
        <a-row :gutter="24">
          <!-- 我的标签 -->
          <div class="tags-header">
            <a-icon type="pushpin" theme="filled" />
            <span>我的标签</span>
          </div>
          <div class="tags-content">
            <div>
              <template v-for="tag in informData.selectLabel">
                <a-tag
                  :key="tag.id"
                  :style="{fontSize: tag.length >= 6 ? '10px' : '16px'}"
                  class="tag-default"
                  :class="{'attention-tag':tag.isSelect === true}"
                >{{ tag.label}}</a-tag>
              </template>
            </div>
            <div>
              <template v-for="(tag) in informData.inputLabel">
                <a-badge :key="tag.id" class="tag-badge">
                  <a-icon
                    slot="count"
                    :key="tag.id"
                    type="close-circle"
                    theme="filled"
                    class="tag-icon"
                    @click="handleClose(tag.id)"
                  ></a-icon>
                  <a-tag :key="tag.id" class="tag-add">{{ tag.label }}</a-tag>
                </a-badge>
              </template>

              <a-input
                v-if="inputVisible"
                ref="input"
                type="text"
                class="tag-input"
                :value="inputValue"
                @change="handleInputChange"
                @blur="handleInputConfirm($event)"
                @keyup.enter="handleInputConfirm($event)"
              />
              <a-tag class="tag-span-add" @click="showInput">添加标签</a-tag>
            </div>
          </div>
        </a-row>
      </a-form-model>
      <template slot="footer">
        <div class="inform-footer">
          <a-button class="submit-btn" type="primary" @click="submitForm('form')">确定</a-button>
          <a-button class="close-btn" @click="handleCancel()">关闭</a-button>
        </div>
      </template>
    </a-modal>
    <!-- 修改手机号弹框 -->
    <a-modal
      class="mobile-modal common-dialog"
      title="修改手机号"
      width="800px"
      :visible="mobileFormVisible"
      @cancel="mobilehandleCancel"
    >
      <a-form :form="mobileForm" class="mobile-content">
        <a-form-item>
          <a-input
            v-decorator="[
            'mobile',
            { rules: [{ required: true,message: '请输入当前手机号'},{message:'手机号码格式不正确',pattern:/^1[3456789]\d{9}$/}] }
          ]"
            type="text"
            autocomplete="off"
            :maxLength="11"
            placeholder="当前手机号"
            disabled
          >
            <a-icon
              slot="prefix"
              class="password-tip"
              type="mobile"
              style="color: rgba(0,0,0,.25)"
            />
          </a-input>
        </a-form-item>
        <a-form-item>
          <a-input
            v-decorator="[
            'newMobile',
            { rules: [{ required: true,message: '请输入新手机号'},{message:'手机号码格式不正确',pattern:/^1[3456789]\d{9}$/}
            ,{validator:newMobileValidate}]}
          ]"
            type="text"
            autocomplete="off"
            :maxLength="11"
            placeholder="新手机号"
            @focus="newMobileTooltip=true"
            @blur="newMobileTooltip=false"
          >
            <a-tooltip :visible="newMobileTooltip" slot="prefix" title="11位数字" placement="topLeft">
              <a-icon class="password-tip" type="mobile" style="color: rgba(0,0,0,.25)" />
            </a-tooltip>
          </a-input>
        </a-form-item>
        <a-form-item class="verify-code">
          <a-input
            v-decorator="[
            'verifyCode',
            { rules: [{ required: true, message: '请输入验证码'},{message:'只允许输入数字',pattern:/^[0-9]*$/ }] }
          ]"
            :maxLength="4"
            placeholder="验证码"
          >
            <a-icon slot="prefix" type="safety" style="color: rgba(0,0,0,.25)" />
          </a-input>
          <span
            :class="{'get-code':true,'get-code-clickable':btnText==='获取验证码'?true:false}"
            @click="getCode"
            v-text="btnText"
          ></span>
        </a-form-item>
      </a-form>
      <template slot="footer">
        <div class="inform-footer">
          <a-button key="submit" class="submit-btn" type="primary" @click="mobileSubmit">确定</a-button>
          <a-button class="close-btn" @click="mobilehandleCancel()">关闭</a-button>
        </div>
      </template>
    </a-modal>
  </div>
</template>

<script>
import {
  getCode,
  checkMobile,
  updateMobile,
  saveLabelInput,
  deleteLabelInput,
  saveUserInfo,
} from "@/api/login";
import { VueCropper } from "vue-cropper";
import { uploadAvatar } from "@/api/login";
import AvatarUpload from "./userAvatarUpload";
export default {
  components: {
    VueCropper,
    AvatarUpload,
  },
  props: {
    saveFunc: {
      type: Function,
      default: () => {},
    },
    informData: {
      type: Object,
      default: null,
    },
    informVisible: {
      type: Boolean,
      default: false,
    },
    closeFunc: {
      type: Function,
      default: () => {},
    },
  },
  data() {
    return {
      formLayout: {
        labelCol: { span: 4 },
        wrapperCol: { span: 10 },
      },
      btnText: "获取验证码",
      mobileFormVisible: false,
      isPhoneEdit: false,
      isEmailEdit: false,
      newMobileTooltip: false,
      userPhone: "",
      rules: {
      },
      //添加标签input显示
      inputVisible: false,
      inputValue: "",
      codeFlag: false, //弹框显示后 是否点击过获取验证码标识
      userEmail: "",
    };
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {
    informData: {
      handler(newV) {
        this.userPhone = this.informData.mobile;
        console.log(this.informData);
      },
      deep: true,
    },
  },
  mounted() {
    this.userPhone = this.informData.mobile;
  },
  beforeCreate() {
    this.mobileForm = this.$form.createForm(this, { name: "normal_mobile" });
  },
  //方法集合
  methods: {
    //修改手机号 提交
    mobileSubmit(e) {
      e.preventDefault();
      let that = this;
      let mobile = that.mobileForm.getFieldValue("newMobile");
      if (!mobile) {
        that.$message.destroy();
        that.$message.warning("请输入新手机号");
        return;
      }
      const flag = /^1[3456789]\d{9}$/.test(mobile);
      if (!flag) {
        that.$message.destroy();
        that.$message.warning("新手机号码格式不正确");
        return;
      }
      checkMobile({
        mobile: that.mobileForm.getFieldValue("newMobile"),
        smsCode: "CODE-004",
      })
        .then((res) => {
          if (res.data) {
            //修改手机号 新手机号存在
            that.$message.destroy();
            that.$message.error("手机号已存在，请重新输入新手机号");
            return false;
          }
          if (!that.codeFlag) {
            that.$message.destroy();
            that.$message.warning("请先获取验证码");
            return false;
          }
          that.mobileForm.validateFields((err, values) => {
            if (!err) {
              let param = Object.assign({}, values);
              updateMobile(param)
                .then((res) => {
                  that.$message.success("修改成功~");
                  that.mobileFormVisible = false;
                  that.informData.mobile = values.newMobile;
                })
                .catch((err) => {
                  that.$message.destroy();
                  that.$message.error(err);
                });
            }
          });
        })
        .catch((err) => {
          that.$message.destroy();
          that.$message.error(err);
        });
    },
    //新手机号
    newMobileValidate(rule, value, callback) {
      if (value && value === this.informData.mobile) {
        callback("新手机号不能与当前手机号相同!");
      } else {
        callback();
      }
    },
    //获取验证码  CODE-004 修改手机号验证码
    getCode() {
      if (this.btnText === "获取验证码") {
        let mobile = this.mobileForm.getFieldValue("newMobile");
        if (!mobile) {
          this.$message.destroy();
          this.$message.warning("请输入接收验证码的新手机号");
          return;
        }
        const flag = /^1[3456789]\d{9}$/.test(mobile);
        if (!flag) {
          this.$message.destroy();
          this.$message.warning("手机号码格式不正确");
          return;
        }
        let that = this;
        checkMobile({ mobile: mobile, smsCode: "CODE-004" })
          .then((res) => {
            if (res.data) {
              //修改手机号 新手机号存在
              that.$message.destroy();
              that.$message.error("手机号已存在，请重新输入新手机号");
              return false;
            }
            getCode({ mobile: mobile, smsCode: "CODE-004" })
              .then((res) => {
                that.codeFlag = true;
                that.$message.success("短信发送成功，请注意查收");
                // 设置定时器，发送验证码
                let num = 119;
                that.btnText = `${num}s后重新获取`;
                that.myInterval = setInterval(() => {
                  if (num < 1) {
                    clearInterval(that.myInterval);
                    that.btnText = "获取验证码";
                  } else {
                    num--;
                    that.btnText = `${num}s后重新获取`;
                  }
                }, 1000);
              })
              .catch((err) => {
                that.$message.destroy();
                that.$message.error(err || "短信发送失败，请稍后重试!");
                clearInterval(that.myInterval);
                that.btnText = "获取验证码";
              });
          })
          .catch((err) => {
            that.$message.destroy();
            that.$message.error(err);
          });
      }
    },
    //关闭标签事件
    handleClose(id) {
      deleteLabelInput(id)
        .then((res) => {
          this.$message.success("删除成功");
          this.$emit("refreshLabelInput");
        })
        .catch((err) => {
          this.$message.destroy();
          this.$message.error(err);
        });
    },
    //添加标签事件
    showInput() {
      this.inputVisible = true;
      this.$nextTick(function () {
        this.$refs.input.focus();
      });
    },
    //添加标签inputchange事件
    handleInputChange(e) {
      this.inputValue = e.target.value;
    },
    //确认添加标签事件
    handleInputConfirm(e) {
      console.log(e);
      const inputValue = this.inputValue;
      if (inputValue === "") {
        this.$message.destroy();
        // this.$message.warning("输入内容不能为空");
        this.inputVisible = false;
        return;
      }
      var param = {
        isSelect: true,
        label: this.inputValue,
        sort: 0,
        type: 2,
      };
      saveLabelInput(param)
        .then((res) => {
          Object.assign(this, {
            inputVisible: false,
            inputValue: "",
          });
          this.$message.destroy();
          this.$message.success("添加成功");
          this.$emit("refreshLabelInput");
        })
        .catch((err) => {
          this.$message.destroy();
          this.$message.error(err);
        });
    },
    //修改手机号
    mobileEdit() {
      this.mobileFormVisible = true;
      this.mobileForm.resetFields();
      this.$nextTick(() => {
        this.mobileForm.setFieldsValue({ mobile: this.informData.mobile });
      });
    },
    //修改邮箱
    emailEdit() {
      this.isEmailEdit = true;
      this.userEmail = this.informData.email;
    },
    //表单提交事件
    submitForm() {
      if (this.informData.email == "") {
        this.$message.destroy();
        this.$message.warning("请输入邮箱!");
        return false;
      }
      const isEmail = /^[a-zA-Z0-9._%+-]+@(?!.*\.\..*)[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
      if (this.informData.email && !isEmail.test(this.informData.email)) {
        this.$message.destroy();
        this.$message.warning("邮箱的格式不正确!");
        return false;
      }
      this.isPhoneEdit = false;
      this.isEmailEdit = false;

      console.log("修改：", this.informData);
      //请求提交接口
      saveUserInfo(this.informData).then((res) => {
        console.log("提交响应：", res);
        this.$message.destroy();
        this.$message.success("修改成功~");
      });
      this.$emit("saveFunc");
    },
    //重置表单
    resetForm() {
      this.$refs.form.resetFields();
    },
    //提交修改邮箱
    emailSubmit(e) {
      this.isEmailEdit = false;
    },
    //取消修改邮箱
    cancelEmailSubmit() {
      console.log("取消：", this.userEmail);
      this.isEmailEdit = false;
      this.informData.email = this.userEmail;
    },
    //弹窗关闭
    handleCancel(e) {
      console.log("点击了取消按钮");
      this.$emit("closeFunc");
    },
    mobilehandleCancel() {
      this.mobileFormVisible = false;
    },
    /**用户更改头像 */
    uploadOk(photoUrl) {
      console.log("触发了uploadOk方法:", photoUrl);
      this.informData.photo = photoUrl;
    },
  },
};
</script>
<style lang='stylus' scoped>
.inform-form
  .info-header
    margin-bottom 10px
    span
      margin-left 8px
      font-size 14px
      font-weight 600
  span
    font-size 16px
    margin-left 8px
    color #333333
  .input-unitName
    width 100%
    font-size 16px
    font-weight 500
  .iconfont
    margin 0px 0px 0px 8px
    cursor pointer
    color #87d068
  .tags-header
    span
      margin-left 8px
      font-size 14px
      font-weight 600
  .tags-content
    .tag-default
      background #F5F5F5
      border 0px
      color #B8B8B8
      margin-bottom 10px
    .tag-attention
      background #089DFF
      border 0px
      color #fff
      cursor pointer
    .tag-add
      background #089DFF
      border 0px
      color #fff
      cursor pointer
      margin-bottom 10px
    .tag-input
      width 100px
      padding 8px
      margin 0px 8px
      border-radius 30px
      height 38px
      background #F5F5F5
      border 0px
      color #000
      text-align center
    .tag-span-add
      color #1678FD
      font-size 14px
      border 0px
      background #fff
      cursor pointer
    .tag-badge
      position relative
      margin-left 0
    .tag-badge >.tag-icon
      display none
    .tag-badge:hover >.tag-icon
      display block
      position absolute
      right 8%
      top 10%
      font-size 20px
      color #FF8B19
      background #fff
      border-radius 50%
    .attention-tag
      color #fff
      font-size 14px
      background #089dff
.inform-footer
  .submit-btn
    width 76px
    height 34px
    margin 0px 20px
    border 1px solid #1678FD
    background #1678FD
  .close-btn
    width 76px
    height 34px
    margin 0px 20px
    border 1px solid #1678FD
    color #1678FD
.mobile-content
  width 60%
  margin 0 auto
  height 516px
</style>